package com.industrial.im.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import com.industrial.common.core.domain.R;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.StringUtils;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.im.domain.DispatchKeyItemManagement;
import com.industrial.im.domain.DispatchKeyItemManagementSchedule;
import com.industrial.im.domain.vo.ItemDetailVo;
import com.industrial.im.domain.vo.TaskVo;
import com.industrial.im.mapper.DispatchKeyItemManagementMapper;
import com.industrial.im.service.IDispatchKeyItemManagementSchedulerService;
import com.industrial.im.service.IDispatchKeyItemManagementService;
import com.industrial.system.api.RemoteUserService;
import com.industrial.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.industrial.im.mapper.DispatchTaskExecutionManageMapper;
import com.industrial.im.domain.DispatchTaskExecutionManage;
import com.industrial.im.service.IDispatchTaskExecutionManageService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 任务执行管理Service业务层处理
 * 
 * @author SangGuangCan
 * @date 2024-03-08
 */
@Service
public class DispatchTaskExecutionManageServiceImpl implements IDispatchTaskExecutionManageService 
{
    @Autowired
    private DispatchTaskExecutionManageMapper dispatchTaskExecutionManageMapper;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private DispatchKeyItemManagementMapper dispatchKeyItemManagementMapper;


    @Autowired
    private IDispatchKeyItemManagementService dispatchKeyItemManagementService;

    @Autowired
    private IDispatchKeyItemManagementSchedulerService dispatchKeyItemManagementSchedulerService;
    /**
     * 查询任务执行管理
     * 
     * @param baseId 任务执行管理主键
     * @return 任务执行管理
     */
    @Override
    public DispatchTaskExecutionManage selectDispatchTaskExecutionManageByBaseId(String baseId)
    {
        return dispatchTaskExecutionManageMapper.selectDispatchTaskExecutionManageByBaseId(baseId);
    }

    /**
     * 查询任务执行管理列表
     * 
     * @param dispatchTaskExecutionManage 任务执行管理
     * @return 任务执行管理
     */
    @Override
    public List<DispatchTaskExecutionManage> selectDispatchTaskExecutionManageList(DispatchTaskExecutionManage dispatchTaskExecutionManage)
    {
        return dispatchTaskExecutionManageMapper.selectDispatchTaskExecutionManageList(dispatchTaskExecutionManage);
    }

    /**
     * 新增任务执行管理
     * 
     * @param dispatchTaskExecutionManage 任务执行管理
     * @return 结果
     */
    @Override
    public int insertDispatchTaskExecutionManage(DispatchTaskExecutionManage dispatchTaskExecutionManage)
    {
        return dispatchTaskExecutionManageMapper.insertDispatchTaskExecutionManage(dispatchTaskExecutionManage);
    }

    /**
     * 修改任务执行管理
     * 
     * @param dispatchTaskExecutionManage 任务执行管理
     * @return 结果
     */
    @Override
    public int updateDispatchTaskExecutionManage(DispatchTaskExecutionManage dispatchTaskExecutionManage)
    {
        return dispatchTaskExecutionManageMapper.updateDispatchTaskExecutionManage(dispatchTaskExecutionManage);
    }

    /**
     * 批量删除任务执行管理
     * 
     * @param baseIds 需要删除的任务执行管理主键
     * @return 结果
     */
    @Override
    public int deleteDispatchTaskExecutionManageByBaseIds(String[] baseIds)
    {
        return dispatchTaskExecutionManageMapper.deleteDispatchTaskExecutionManageByBaseIds(baseIds);
    }

    /**
     * 删除任务执行管理信息
     * 
     * @param baseId 任务执行管理主键
     * @return 结果
     */
    @Override
    public int deleteDispatchTaskExecutionManageByBaseId(String baseId)
    {
        return dispatchTaskExecutionManageMapper.deleteDispatchTaskExecutionManageByBaseId(baseId);
    }

    /**
     * 查询列表
     * @return
     */
    @Override
    public List<TaskVo> queryList(TaskVo taskVo) {

        Set<String> roles = SecurityUtils.getLoginUser().getRoles();
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
//        public static final String PROVINCE = "p_01_011";
//        public static final String CITY = "s_01_011";
//        public static final String COUNTY = "x_01_011";

        if(sysUser.isAdmin()){
            roles.add("p_01_011");
        }

        if(ArrayUtil.contains(roles.toArray(),"x_01_011")){
            taskVo.setCounty(sysUser.getDistrict());
        }else if(ArrayUtil.contains(roles.toArray(),"s_01_011")){
            taskVo.setCity(sysUser.getCity());
        }else if(ArrayUtil.contains(roles.toArray(),"p_01_011")){
            taskVo.setProvince(sysUser.getProvince());
        }

        List<TaskVo> r = dispatchTaskExecutionManageMapper.queryList(taskVo);

        if(r != null && !r.isEmpty()){

            //设置工作进度
            for(TaskVo tempR : r){
                //设置工作进度
                List<DispatchKeyItemManagementSchedule> scheduleList = tempR.getScheduleList();
                if(scheduleList != null && !scheduleList.isEmpty()){
                    scheduleList = scheduleList.stream().sorted(Comparator.comparing(DispatchKeyItemManagementSchedule::getBaseCreateTime).reversed()).collect(Collectors.toList());
                    DispatchKeyItemManagementSchedule dispatchKeyItemManagementSchedule = scheduleList.get(0);
                    if(dispatchKeyItemManagementSchedule != null){
                        String schedule = dispatchKeyItemManagementSchedule.getSchedule();
                        tempR.setComDegree(schedule);
                    }else{
                        tempR.setComDegree("0");
                    }
                }else{
                    tempR.setComDegree("0");
                }
            }

            //负责人Id
            List<String> mainHeaderList = r.stream().map(TaskVo::getItemMain).collect(Collectors.toList());
            //创建人ID
            List<String> createList = r.stream().map(TaskVo::getBaseCreateBy).collect(Collectors.toList());
            //参与人ID
//            List<String> cyrList = r.stream().map(TaskVo::getItemParticipants).collect(Collectors.toList());
//            List<String> cyrNewList = new ArrayList<>();
//
//            for(String cyrTemp : cyrList){
//                if(StringUtils.isNotBlank(cyrTemp)){
//                    String[] cyrSz = cyrTemp.split(",");
//                    List<String> cyrArgs = Arrays.asList(cyrSz);
//                    cyrNewList.addAll(cyrArgs);
//                }
//            }

            List<String> params = new ArrayList<>();
            params.addAll(mainHeaderList);
            params.addAll(createList);
//            params.addAll(cyrNewList);

            params = params.stream().distinct().collect(Collectors.toList());
            //完程调用System服务，查询出用户的nickName
            R<List<SysUser>> listR = remoteUserService.queryUserInfoByUserIds(params);
            if(listR.getCode() == R.SUCCESS){
                List<SysUser> userInfoList = listR.getData();
                if(userInfoList != null && !userInfoList.isEmpty()){
                    Map<String, String> userInfoMap = userInfoList.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getNickName));
                    for(TaskVo tempR : r){
                        //修改负责人的NickName
                        String itemMainUserId = tempR.getItemMain();
                        String itemMainNickName = userInfoMap.get(itemMainUserId);
                        tempR.setItemMain(itemMainNickName);

//                        String itemParticipants = tempR.getItemParticipants();
//                        if(StringUtils.isNotBlank(itemParticipants)){
//                            String[] participantsUserIds = itemParticipants.split(",");
//                            StringBuilder participantsUserNickNameStr = new StringBuilder();
//                            for(String participantsUserId : participantsUserIds){
//                                String participantsUseNickName = userInfoMap.get(participantsUserId);
//                                participantsUserNickNameStr.append(participantsUseNickName).append(",");
//                            }
//                            tempR.setItemParticipants(participantsUserNickNameStr.toString());
//                        }


                        //重新设置下发人NickName
                        String baseCreateByUserId = tempR.getBaseCreateBy();
                        String baseCreateByUserNickName = userInfoMap.get(baseCreateByUserId);
                        tempR.setBaseCreateBy(baseCreateByUserNickName);
                    }
                }
            }
        }
        return r;
    }



    /**
     * <p>
     *     查询签收的负责人
     * </p>
     * @param itemId 事项的ID
     * @return
     */
    @Override
    public List<SysUser> queryMainHeader(String itemId) {

        //通过事项ID查询事项的信息
        DispatchKeyItemManagement dispatchKeyItemManagement = dispatchKeyItemManagementMapper.selectDispatchKeyItemManagementByBaseId(itemId);
        if(dispatchKeyItemManagement != null){
            String createUserId = dispatchKeyItemManagement.getBaseCreateBy();
            if(StringUtils.isBlank(createUserId)){
                throw new RuntimeException("未找到事项的创建人");
            }

            //远程调用System服务查询和创建人在同一部门下的所有用户
            R<List<SysUser>> listR = remoteUserService.queryUserInDeptAllUser(createUserId);
            if(listR.getCode() == R.SUCCESS){
                List<SysUser> userInfo = listR.getData();
                return userInfo;
            }
        }
        return new ArrayList<SysUser>();
    }

    /**
     * <p>
     * 保存事项负责人和事项参与人
     * </p>
     *
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveMainHeaderAndCyrInfo(DispatchTaskExecutionManage params) {

        String pkId = params.getPkId();
        DispatchTaskExecutionManage queryTaskParams = new DispatchTaskExecutionManage();
        queryTaskParams.setPkId(pkId);
        List<DispatchTaskExecutionManage> dispatchTaskExecutionManages = dispatchTaskExecutionManageMapper.selectDispatchTaskExecutionManageList(queryTaskParams);
        if(!dispatchTaskExecutionManages.isEmpty()){
            throw new RuntimeException("您已签收,无须再次签收");
        }

        params.setBaseId(IdUtil.simpleUUID());
        params.setBaseCreateBy(SecurityUtils.getUserId());
        params.setBaseCreateTime(DateUtils.getNowDate());
        params.setBaseUpdateBy(SecurityUtils.getUserId());
        params.setBaseUpdateTime(DateUtils.getNowDate());

        params.setSigningTime(DateUtils.getNowDate());
        dispatchTaskExecutionManageMapper.insertDispatchTaskExecutionManage(params);
        DispatchKeyItemManagement updateParams = new DispatchKeyItemManagement();
        updateParams.setBaseId(pkId);
        updateParams.setItemStatus("1");
        dispatchKeyItemManagementMapper.updateDispatchKeyItemManagementStatus(updateParams);
    }


    /**
     * 查询事项页面详情
     *
     * @param baseId
     * @return
     */
    @Override
    public ItemDetailVo queryItemDetailInfo(String baseId) {

        ItemDetailVo itemDetailVo = new ItemDetailVo();

        //查询计划信息
        DispatchTaskExecutionManage dispatchTaskExecutionManage = dispatchTaskExecutionManageMapper.selectDispatchTaskExecutionManageByBaseId(baseId);

        itemDetailVo.setSignTime(dispatchTaskExecutionManage.getSigningTime());
        itemDetailVo.setItemParticipants(dispatchTaskExecutionManage.getItemParticipants());
        itemDetailVo.setSignTime(dispatchTaskExecutionManage.getSigningTime());
        //获取重点事项的信息
        String pkId = dispatchTaskExecutionManage.getPkId();
        DispatchKeyItemManagement dispatchKeyItemManagement = dispatchKeyItemManagementService.selectDispatchKeyItemManagementByBaseId(pkId);

        //查询工作进度信息
        List<DispatchKeyItemManagementSchedule> scheduleList = dispatchKeyItemManagementSchedulerService.selectDispatchKeyItemManagementSchedulerListByPkId(dispatchTaskExecutionManage.getBaseId());
        if(scheduleList != null && !scheduleList.isEmpty()){
            scheduleList = scheduleList.stream().sorted(Comparator.comparing(DispatchKeyItemManagementSchedule::getBaseCreateTime).reversed()).collect(Collectors.toList());
            //总进度
            String scheduleSum = scheduleList.get(0).getSchedule();
            itemDetailVo.setSchedule(scheduleSum);
            itemDetailVo.setScheduleList(scheduleList);
        }else{
            itemDetailVo.setSchedule("0");
            itemDetailVo.setScheduleList(new ArrayList<>());
        }

        //设置用户昵称
        //设置参与人
//        String itemParticipants = dispatchTaskExecutionManage.getItemParticipants();
        //设置事项负责人
        String itemMain = dispatchTaskExecutionManage.getItemMain();

        List<String> userIdList = new ArrayList<>();
        userIdList.add(itemMain);

        Map<String, String> userInfoMap = new HashMap<>();

//        if(StringUtils.isNotBlank(itemParticipants)){
//            String[] participantsUserId = itemParticipants.split(",");
//            for(String t : participantsUserId){
//                userIdList.add(t);
//            }
//            userIdList = userIdList.stream().distinct().collect(Collectors.toList());
//            R<List<SysUser>> userInfoList = remoteUserService.queryUserInfoByUserIds(userIdList);
//            if(userInfoList.getCode() == R.SUCCESS){
//                List<SysUser> data = userInfoList.getData();
//                userInfoMap = data.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getNickName));
//            }
//        }

        if(userIdList != null && !userIdList.isEmpty()){
            R<List<SysUser>> userInfoList = remoteUserService.queryUserInfoByUserIds(userIdList);
            if(userInfoList.getCode() == R.SUCCESS){
                List<SysUser> data = userInfoList.getData();
                userInfoMap = data.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getNickName));
            }
        }

        if(StringUtils.isNotBlank(itemMain)){
            String userNickName = userInfoMap.get(itemMain);
            itemDetailVo.setItemMain(userNickName);
        }


//        if(StringUtils.isNotBlank(itemParticipants)) {
//            String[] participantsUserId = itemParticipants.split(",");
//            StringBuilder nickNameStr = new StringBuilder();
//            for(String t : participantsUserId){
//                String nickName = userInfoMap.get(t);
//                nickNameStr.append(nickName).append(",");
//            }
//            itemDetailVo.setItemParticipants(nickNameStr.toString());
//        }



        itemDetailVo.setStartTime(dispatchKeyItemManagement.getStartTime());
        itemDetailVo.setEndTime(dispatchKeyItemManagement.getEndTime());
        itemDetailVo.setBaseCreateTime(dispatchKeyItemManagement.getBaseCreateTime());
        itemDetailVo.setBaseCreateBy(dispatchKeyItemManagement.getBaseCreateBy());
        itemDetailVo.setItemType(dispatchKeyItemManagement.getItemType());
        itemDetailVo.setItemDesc(dispatchKeyItemManagement.getItemDesc());
        return itemDetailVo;
    }
}
